﻿using System;
using System.Linq;

using Autofac;

using Cookbook.Services.Core.Commanding;
using Cookbook.Services.Core.Common;
using Cookbook.Services.Core.Handlers;
using Cookbook.Services.Core.Persistency;

using Cooking.Services.Specs.Support;

namespace Cooking.Services.Specs.Builders
{
    internal class BatchedCommandExecutorBuilder : TestDataBuilder<BatchedCommandExecutor>
    {
        private InMemoryDataMapper dataMapper = new InMemoryDataMapper();

        protected override BatchedCommandExecutor OnBuild()
        {
            var builder = new ContainerBuilder();

            builder.Register(c => new CookbookUnitOfWork(dataMapper)).ExternallyOwned();
            builder.RegisterInstance<ILogger>(new NullLogger());
            builder.RegisterType<BatchedCommandExecutor>();

            builder
                .RegisterAssemblyTypes(typeof(BatchedCommandExecutor).Assembly)
                .Where(IsCommandHandler)
                .AsImplementedInterfaces();

            var container = builder.Build();

            return container.Resolve<BatchedCommandExecutor>();
        }

        private static bool IsCommandHandler(Type type)
        {
            return !type.IsAbstract && 
                    type.GetInterfaces().Any(i => i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(IHandles<>)));
        }

        public BatchedCommandExecutorBuilder Using(InMemoryDataMapper dataMapper)
        {
            this.dataMapper = dataMapper;
            return this;
        }
    }
}